package com.juc.future;

import java.util.concurrent.*;

/**
 * @Author Zan
 * @Create 2024/5/6 20:59
 * @ClassName : CompletableFutureUseDemo
 * @Description : TODO 请用一句话描述该类的功能
 */
public class CompletableFutureUseDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try {
            CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName() + "----come in");
                int result = ThreadLocalRandom.current().nextInt(10);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("--------1秒钟后出结果：" + result);
                if (result > 5) {
                    int i = 10 / 0;
                }
                return result;
            }, threadPool).whenComplete((v, e) -> { // 成功的情况下
                if (e == null) { // 没有报错
                    System.out.println("--------计算完成，更新系统UpdateValue：" + v);
                }
            }).exceptionally((e) -> { // 报错的情况下，异常的情况下
                e.printStackTrace();
                System.out.println("异常情况：" + e.getCause() + "\t" + e.getStackTrace());
                return null;
            });
            System.out.println(Thread.currentThread().getName() + "\t ----忙其他任务了");
            System.out.println(completableFuture.get());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }

    private static void future1() throws InterruptedException, ExecutionException {
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "----come in");
            int result = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("--------1秒钟后出结果：" + result);
            return result;
        });

        System.out.println(Thread.currentThread().getName() + "\t ----忙其他任务了");

        System.out.println(completableFuture.get());
    }
}
